package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsAdminStrongService;
import com.qf.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.xml.ws.RequestWrapper;
import java.util.Date;

@Service
public class DtsAdminStrongServiceImpl implements DtsAdminStrongService {
    @Autowired
    DtsStorageMapper storageMapper;



    @Override
    public IPage<DtsStorage> findBYpage(Integer page, Integer limit, String sort, String order, String key, String name) {
        IPage<DtsStorage> ipage = new Page<>(page,limit);
        QueryWrapper<DtsStorage> qw = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            qw.eq("`key`",key);
        }
        if (!StringUtils.isEmpty(name)){
            qw.like("name",name);
        }

        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)){
            if(order.equalsIgnoreCase("desc")) {
                qw.orderByDesc(sort);
            }else {
                qw.orderByAsc(sort);
            }
        }

        storageMapper.selectPage(ipage, qw);
        return ipage;
    }
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;


    @Override
    public DtsStorage add(byte[] bytes, String key, String name, int size, String contentType) throws Exception {
        String url = AliyunOSSUtil.uploadImage(endpoint,accessKeyId,accessKeySecret,bucketName,name,bytes);
        //保存到数据中
        DtsStorage storage = new DtsStorage();
        storage.setUpdateTime(new Date());
        storage.setAddTime(new Date());
        storage.setDeleted(false);
        storage.setName(name); //原始文件名
        storage.setKey(key); //唯一的名称
        storage.setSize(size);
        storage.setType(contentType);
        storage.setUrl(url);
        storageMapper.insert(storage);
        return storage;
    }

    @Override
    public void deleteById(DtsStorage storage) {
        storageMapper.deleteById(storage.getId());
        AliyunOSSUtil.deleteFile(endpoint,accessKeyId,accessKeySecret,bucketName,storage.getKey());
    }

    @Override
    public void update(DtsStorage storage) {
        storageMapper.updateById(storage);
    }
}
